package com.smartum.mpr.business;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.smartum.mpr.dao.ItemDao;
import com.smartum.mpr.dao.ItemPurchaseDao;
import com.smartum.mpr.exception.AuthorizationException;
import com.smartum.mpr.exception.DatabaseIntegrityException;
import com.smartum.mpr.exception.NotCorrectPermission;
import com.smartum.mpr.exception.NotExistsTokenException;
import com.smartum.mpr.model.Item;
import com.smartum.mpr.model.ItemImage;
import com.smartum.mpr.model.ItemPurchase;
import com.smartum.mpr.model.User;
import com.smartum.mpr.util.BackendConfig;

@Service
public class ItemBusiness extends BaseBusiness {

	@Autowired
	private ItemDao itemDao;
	@Autowired
	private ItemPurchaseDao purchaseDao;

	public List<Item> getAllItems() {
		List<Item> items = itemDao.getList();
		for (Item item : items) {
			changeItemImagesPath(item);
		}
		return items;
	}

	public void saveItem(Item item) {
		itemDao.save(item);
	}

	public void checkPostPermission(Long userId, Long categoryId) throws DatabaseIntegrityException,
	        AuthorizationException, NotExistsTokenException, NotCorrectPermission {
		ItemPurchase purchase = purchaseDao.getItemPurchase(categoryId, userId);
		if (purchase == null) {
			throw new NotCorrectPermission("no_permission_to_post_item");
		}
	}

	public void removePostPermission(Long userId, Long categoryId) throws DatabaseIntegrityException,
	        AuthorizationException, NotExistsTokenException, NotCorrectPermission {
		ItemPurchase purchase = purchaseDao.getItemPurchase(categoryId, userId);
		if (purchase == null) {
			throw new NotCorrectPermission("no_permission_to_post_item");
		}else{
			purchaseDao.deletePurchase(purchase);
		}
	}

	public Item getItem(Long id) {
		Item item = itemDao.get(id);
		changeItemImagesPath(item);
		return item;
	}

	public List<Item> getUserItems(Long userId, Long timestamp, int amount) {
		List<Item> items = itemDao.getUserItems(userId, timestamp, amount);
		for (Item item : items) {
			changeItemImagesPath(item);
		}
		return items;
	}

	public List<Item> searchItems(Long categoryId, Long subCategoryId, Boolean getHeighest, Long timestamp, int amount,
	        Long countyId) {
		List<Item> items = itemDao.getItemsBySearchQuery(categoryId, subCategoryId, getHeighest, timestamp, amount,
		        countyId);
		for (Item item : items) {
			changeItemImagesPath(item);
		}
		return items;
	}

	public void deleteItem(Long itemId) {
		itemDao.delete(itemId);
	}

	public void changeImagePathInItemImage(ItemImage image) {
		String appUrl = BackendConfig.getInstance().getAppUrl();
		String imagePath = image.getImagePath();
		image.setImagePath(appUrl + imagePath);
	}

	private void changeItemImagesPath(Item item) {
		for (ItemImage image : item.getItemImages()) {
			changeImagePathInItemImage(image);
		}
	}
}
